package com.web;


import com.dao.Impl.goodDAOImpl;
import com.entity.goods;
import com.google.gson.Gson;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/addGood")
public class AddGoodServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进来了");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String id = req.getParameter("id");
        String name = req.getParameter("name");
        double price = Double.parseDouble(req.getParameter("price"));
        String date = req.getParameter("date");
        int xiajia = Integer.parseInt(req.getParameter("xiajia"));
        goods good = new goods(id,name,price,date,xiajia);
        int count = new goodDAOImpl().addGood(good);
        resp.setContentType("application/json");
        PrintWriter out = resp.getWriter();
        Gson gson = new Gson();
        if(count > 0){
            List<goods> list = new goodDAOImpl().ListGoods();
            req.setAttribute("list",list);
            out.write(gson.toJson(list));
        }else{
            resp.sendRedirect("index.html");
            out.write(gson.toJson("{\"message\":\"数据接收失败\"}"));
        }
    }

}
